/**
 * @Date 2025/1/2 9:23
 * @Created by 衡盛永
 */

package org.example.deploy.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j//日志
@Component//丢到springboot里   一定不要忘记把处理器加到Ioc容器中!
public class MyMetaObjectHandler implements MetaObjectHandler {//extends??

    @Override//插入时的填充策略
    public void insertFill(MetaObject metaObject) {
        // 先判断是否存在该字段
        boolean createTime = metaObject.hasSetter("createTime");
        if (createTime) {
            log.info("==start insert ······==");
            //setFieldValByName(java.lang.String fieldName, java.lang.Object fieldVal, org.apache.ibatis.reflection.MetaObject metaObject)
            this.setFieldValByName("createTime", new Date(), metaObject);
            this.setFieldValByName("updateTime", new Date(), metaObject);
        }
    }

    @Override//更新时的填充策略
    public void updateFill(MetaObject metaObject) {
        // 先判断该值是否为空，为空才填充
        Object updateTime = getFieldValByName("updateTime", metaObject);
        if (updateTime != null) {
            log.info("==start update ······==");
            this.setFieldValByName("updateTime", new Date(), metaObject);
        }
    }
}